package FileHandling;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

/**
 * Handles opening/closing/reading(scanning) of files.
 * 
 * @author Lewis Marhin and John Gray-Spence
 */
public class FileOps {

    /**
     * Reads a file into a string.
     *
     * @param fname Name of the file to be opened. Throws IOException if file does not exist.
     * @return String containing file contents.
     */
    public static String readFile( String fname ) {
        String str = "";
        try {
        Scanner reader = new Scanner( fname );

        while ( reader.hasNextLine() ) {
            str = str + reader.nextLine();
        }
        reader.close();
        } catch ( Exception e ) {
            System.out.println("Error encountered while opening file.");
        } finally {
            return str;
        }
    }

    /**
     * Creates a new mindmap file.
     *
     * @param fname Name of the mindmap file to be written. Extension not required.
     * @param map The map data itself.
     * @return Returns string containing successfull/unsuccessfull save message.
     */
    public static String newFile( String fname, String map ) {
        try {
            FileWriter out = new FileWriter( fname + ".mm" );
            out.write(map);
            out.close();
        } catch( IOException e ) {
            return "Error writing file.\nERROR:\n" + e.toString();
        }
        return "File written successfully.";
    }
}
